#!/usr/bin/python
# -*- coding: UTF-8 -*-

from monitor.base import MonitorBase
from config.config import (
    COMMON_INTERVALTIME,
    ALARM_CPU_PERCENTAGE_LIMIT,
    ALARM_CPU_EXCEPT_MAX_NUM,
)
from utils.log.log import Log
from utils.smtp.smtp import Smtp
from utils.utils import (
    get_host_ip,
    get_host_name,
)
import psutil as p

log = Log("cpu monitor")


class CpuMonitor(MonitorBase):
    """ cpu monitor """

    def __init__(self):
        super(CpuMonitor, self).__init__(COMMON_INTERVALTIME)
        self.smtp = None
        self.num = 0

    def Init(self):
        """Init(self)"""
        log.Debug("cpu init xxxx")
        self.smtp = Smtp()
        self.num = 0

    def Check(self):
        """Check(self)"""
        cpu_per = p.cpu_percent()
        log.Debug("cpu_percent=", cpu_per)
        if cpu_per > ALARM_CPU_PERCENTAGE_LIMIT:
            self.num = self.num + 1
            log.Debug(
                "cpu_percent except appear %d times and max times=%d"
                % (self.num, ALARM_CPU_EXCEPT_MAX_NUM)
            )
            if self.num >= ALARM_CPU_EXCEPT_MAX_NUM:
                log.Debug("cpu_percents=", p.cpu_percent(percpu=True))
                self.smtp.Send(
                    "server %s[%s] appear cpu percentage is too big[%d]"
                    % (get_host_ip(), get_host_name(), cpu_per)
                )
                self.num = 0
        else:
            self.num = 0
